import { useContext, useEffect, useMemo, useState } from 'react';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import Cls from 'classnames';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { UpdateContractBottom } from './UpdateContractBottom';
import { effectMainContract, getBreakUpdateDes, getModifyUpdateDes, ntkoQueryParams } from '../mconfig';
import { DescriptionsType } from '@/components/DescriptionsType';
import { changeNumMoneyToChinese, getKeyRouter, wordHandChildParam, wordToChildParams } from '@/utils';
import { history } from 'umi';
import { OpenContractMainBodyModal } from './OpenContractMainBodyModal';
import { OpenCounterpartModal } from './OpenCounterpartModal';
import { saveToURLWordService } from '../services';
import { getBaseUrl } from '@/services/urlconst';
import { NtkoPlugin } from '@/common/NtkoPluginType';
import { OpenMaterialModal } from './OpenMaterialModal';

export const ContractChangeModifyView = ({ onOpenReadOfdWord }) => {
  /** 引入上下文 */
  const {
    contractDetailInfo,
    updteAddOrEdit: { editContractRun, addContractRun, editRecordContractRun, submitRecordContractRun, addAndSubmitContractRun },
    styleFixCls,
    oldContractInfo,
    contractForm,
    contarctJsonList,
    contractDispatch,
    pageType,
    curRes,
    locationState,
  } = useContext(ConractControllerContext);

  /** 是否超预算百分之10 */
  const [isExceedSumTen, setIsExceedSumTen] = useState<boolean>(false);

  /** 打开合同主体弹框 */
  const [openSubjectModal, setOpenSujbectModal] = useState<boolean>(false);

  /** 选择相对方 */
  const [openCounterpartObj, setOpenCounterpartObj] = useState<boolean>(false);

  /** 保存在线编辑权限 */
  const [saveNtkoQuery, setSaveNtkoQuery] = useState<Record<string, any>>({
    filedUrl: '',
    ntkoWordUrl: '',
  });

  /** 打开选择物料列表 */
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);

  /** 变更事项 */
  const [changeModifyItem, setChangeModifyItem] = useState<Record<string, any>>({
    changeSum: 0, //是否变更合同金额
    changeTerm: 0, //是否变更履约期限
    changePay: 0, //是否变更支付方式
    changeSubject: 0, //是否变更合同主体
    changeOpposite: 0, //是否变更相对方
    changeDetail: 0, //是否变更货物清单
    isPayDisabled: false, // 支付方式是否可修改
    changeOther: 0, //是否变更其他
  });

  /** 表单变化 */
  const onValuesChangeForm = (changeValues: Record<string, any>) => {
    const changeKeyStr: string = Object.keys(changeValues)?.toString();
    if (changeKeyStr == 'sumInTax') {
      const maxNumStr: string = changeNumMoneyToChinese(changeValues?.[changeKeyStr]);
      methods?.setFieldsValue({
        sumInTaxCN: maxNumStr,
      });
    }

    // 编辑
    // if (contractDetailInfo?.id) {
    // const changeKeyStr: string = Object.keys(changeValues)?.toString(); //获取变更字段名
    const allFormValues: Record<string, any> = contractForm?.getFieldsValue(); //获取全部填入表单数据
    if (changeKeyStr == 'processList' || changeKeyStr == 'detailList' || changeKeyStr == 'attachList') {
      const changeKeyList: Record<string, any>[] = allFormValues?.[changeKeyStr]; //获取变更的数据源
      const changeKeyIndx: number = changeValues?.[changeKeyStr]?.length - 1;
      if (changeKeyList[changeKeyIndx]['id']) {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '1';
      } else {
        changeKeyList[changeKeyIndx]['modifyFlag'] = '0';
      }

      // if (changeKeyStr == 'processList' && allFormValues?.['sumInTax']) {
      //   // changeKeyList[changeKeyIndx]['paySum'] = (allFormValues?.['sumInTax'] * changeKeyList[changeKeyIndx]['payNum']) / 100;
      //   const num = (changeKeyList[changeKeyIndx]['paySum'] / allFormValues?.['sumInTax']) * 100;
      //   changeKeyList[changeKeyIndx]['payNum'] = num.toFixed(2);
      // }

      let newChangeList: Record<string, any>[] = changeKeyList?.filter((item: any) => {
        //已有标记数据
        return (item?.id || item?.key) && item?.modifyFlag != null;
      });

      const newFormJsonList: Record<string, any>[] = contarctJsonList[changeKeyStr]?.length > 0 ? contarctJsonList[changeKeyStr] : [];

      newFormJsonList?.forEach((delItem: any) => {
        if (delItem?.modifyFlag == '2') {
          newChangeList?.push(delItem);
        }
      });

      contractDispatch({
        //保存标记后的代码
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          [changeKeyStr]: newChangeList,
        },
      });

      contractForm?.setFieldsValue({
        [changeKeyStr]: allFormValues?.[changeKeyStr],
      });
    }

    if (changeKeyStr == 'payStyle') {
      let newPaylist: Record<string, any>[] = [];
      contractDetailInfo?.processList?.forEach((itemPay: any) => {
        const itemInfo: Record<string, any> = {
          ...itemPay,
          modifyFlag: '2',
        };
        newPaylist?.push(itemInfo);
      });

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          processList: [...newPaylist],
        },
      });
    }
    // }
  };

  /** 打开原合同详情 */
  const openOldContractInfo = () => {
    history.push({
      pathname: `/contractController/getMcontractByID/:${getKeyRouter()}${getKeyRouter()}`,
      state: {
        pageType: 'detail',
        id: oldContractInfo?.id,
        oldModifyType: true,
        pageInfo: oldContractInfo,
        pIDDetailInfo: {
          ...oldContractInfo,
        },
        returnPathName: locationState?.returnPathName,
      },
    });
  };

  /** 保存文件接口回调 */
  const saveToUrlWordCallback = (res: any) => {
    const messageObj = {
      msgFlag: res?.msgFlag,
      msgText: res?.msg,
      msgType: 'uploadFiledRequest',
    };
    wordToChildParams(ntkoBrowser, saveNtkoQuery?.ntkoWordUrl, messageObj);
  };

  /** 保存文件接口 */
  const { wordSaveToURLRun } = saveToURLWordService(saveToUrlWordCallback);

  /** 保存文件回调 */
  const ntkoCallback = (childValue) => {
    const childBase = JSON.parse(childValue);
    if (childBase?.baseUrl && childBase?.baseObj) {
      const fieldUrl: string = childBase?.baseUrl?.split(getBaseUrl());
      wordSaveToURLRun({
        ...childBase,
        baseUrl: fieldUrl?.[1],
      });
    }
  };

  /** 引入在线预览 */
  const ntkoBrowser = useMemo(() => {
    const { ntkoBrowser } = NtkoPlugin(ntkoCallback);
    return ntkoBrowser;
  }, []);

  /** 点击在线预览文件 */
  const onNtkoReadWord = (urlName: string, urlObj: Record<string, any>, onlyRead?: boolean) => {
    const { filedUrl, ntkoWordUrl } = ntkoQueryParams(urlObj, curRes, urlName, onlyRead);
    setSaveNtkoQuery({
      filedUrl,
      ntkoWordUrl,
    });
    const childStr = wordHandChildParam(urlObj);

    const extensBool = ntkoBrowser.ExtensionInstalled();
    if (extensBool) {
      ntkoBrowser?.openWindow(ntkoWordUrl, false, '', childStr);
    }
  };

  /** 获取表格配置  { config, methods }*/
  const { config, methods } =
    pageType == 'modify'
      ? getModifyUpdateDes({
          openOldContractInfo,
          changeModifyItem,
          setChangeModifyItem,
          setOpenSujbectModal,
          openCounterpartModal: setOpenCounterpartObj,
          onNtkoReadWord,
          onOpenReadOfdWord,
          setOpenMaterialModal,
        })
      : getBreakUpdateDes({
          openOldContractInfo,
          onNtkoReadWord,
          onOpenReadOfdWord,
        });

  /** 编辑初始化变更信息 */
  useEffect(() => {
    if (contractDetailInfo && contractDetailInfo?.id) {
      const modifyItem: Record<string, any> = {
        changeSum: contractDetailInfo?.changeSum ? contractDetailInfo?.changeSum : 0,
        changeTerm: contractDetailInfo?.changeTerm ? contractDetailInfo?.changeTerm : 0,
        changePay: contractDetailInfo?.changePay ? contractDetailInfo?.changePay : 0,
        changeSubject: contractDetailInfo?.changeSubject ? contractDetailInfo?.changeSubject : 0,
        changeOpposite: contractDetailInfo?.changeOpposite ? contractDetailInfo?.changeOpposite : 0,
        changeDetail: contractDetailInfo?.changeDetail ? contractDetailInfo?.changeDetail : 0,
        changeOther: contractDetailInfo?.changeOther ? contractDetailInfo?.changeOther : 0,
      };
      setChangeModifyItem({
        ...changeModifyItem,
        ...modifyItem,
      });
    }
  }, [contractDetailInfo?.id]);

  /** 初始化原数据 */
  effectMainContract(oldContractInfo, contractForm, changeModifyItem, setChangeModifyItem, contractDispatch, contarctJsonList, contractDetailInfo);

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '5px 20px' }}>
            <DescriptionsType config={config} onValuesChange={onValuesChangeForm} />
          </ScrollBarLayout>
        </div>

        <UpdateContractBottom
          nextBtnShow={false}
          isBudgetNotBtn={isExceedSumTen}
          setTabsInfoPaneInfo={() => {}}
          addContractRun={addContractRun}
          editContractRun={editContractRun}
          editRecordContractRun={editRecordContractRun}
          submitRecordContractRun={submitRecordContractRun}
          addAndSubmitContractRun={addAndSubmitContractRun}
          requestType={true}
          changeModifyItem={changeModifyItem}
          position="bottom"
          loadMapInfo={[]}
        />
      </div>

      {/* 选择合同主体 */}
      {openSubjectModal && (
        <OpenContractMainBodyModal
          onClose={() => {
            setOpenSujbectModal(false);
          }}
          contractFormName={methods}
          oppositeCode={[oldContractInfo?.creditID]}
        />
      )}
      {/* 选择相对方 */}
      {openCounterpartObj && (
        <OpenCounterpartModal
          onClose={() => {
            setOpenCounterpartObj(false);
          }}
          openModal={openCounterpartObj}
        />
      )}

      {/* 选择物料列表 */}
      {openMaterialModal && (
        <OpenMaterialModal
          isShowModal={openMaterialModal}
          onClose={() => {
            setOpenMaterialModal(false);
          }}
        />
      )}
    </>
  );
};
